package com.infosys.china.server;

import java.util.Map;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.infosys.china.entity.DispatchEntity;
import com.infosys.china.entity.OrderEntity;
import com.infosys.china.mapper.OrderMapper;
import com.rabbitmq.client.Channel;

/**
 * 
 * 补单服务，如果在订单服务表中不存在该订单，则在补单服务中创建
 * 
 * @author Jiayoubing
 * @version [版本号,2020年5月17日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Component
public class SupplementConsumer
{

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = "order_create_queue")
    public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws Exception
    {
        String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), "UTF-8");
        System.out.println("启动补单服务平台" + msg + ",消息id:" + messageId);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String orderId = jsonObject.getString("orderId");
        if (StringUtils.isEmpty(orderId))
        {
            // 日志记录
            return;
        }
        OrderEntity orderEntityResult = orderMapper.findOrderId(orderId);

        // 如果订单表中无数据，则需要补单
        if (StringUtils.isEmpty(orderEntityResult))
        {

            // 补单，往订单表插入数据，通常数据是从日志表中查询数来
            OrderEntity orderEntity = new OrderEntity();
            orderEntity.setName("黄焖鸡米饭");
            // 价格是300元
            orderEntity.setOrderMoney(300d);
            // 商品id
            orderEntity.setOrderId(orderId);
            // 1.先下单，创建订单 (往订单数据库中插入一条数据)

            int orderResult = orderMapper.addOrder(orderEntity);

            System.out.println("补单成功，orderResult:" + orderResult);

        }
        // 手动签收消息,通知mq服务器端删除该消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

    }

}